package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IRegisterService;
import com.cskaoyan.user.service.IuserService;
import jdk.nashorn.internal.ir.annotations.Reference;
import jdk.nashorn.internal.parser.JSONParser;
import org.apache.coyote.OutputBuffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/user")

public class CaptchaController {

    @Autowired
    IKaptchaService kaptchaService;
    @Autowired
    IRegisterService registerService;
    @Autowired
    private IuserService userService;
    /**
     * 获取验证码
     */
    @GetMapping("/kaptcha")
    public ResponseData getKaptchaCode(HttpServletResponse response) {
        KaptchaCodeRequest kaptchaCodeRequest=new KaptchaCodeRequest();
        KaptchaCodeResponse kaptchaCodeResponse=kaptchaService.getKaptchaCode(kaptchaCodeRequest);
        if(kaptchaCodeResponse.getCode().equals(UserRetCode.SUCCESS.getCode())){
            Cookie cookie= CookieUtil.genCookie("kaptcha_uuid",kaptchaCodeResponse.getUuid(),"/",60);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return new ResponseUtil<>().setData(kaptchaCodeResponse.getImageCode());
        }
        return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getCode());
    }

    @PostMapping("/kaptcha")
    public ResponseData validKaptchaCode(@RequestBody String code, HttpServletRequest httpServletRequest) {
        KaptchaCodeRequest request = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        request.setUuid(uuid);
        request.setCode(code);
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(request);
        if (response.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getCode());
    }


    /*
     *用户注册
     *
     * @param request
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author chenxu
     * @since 2022/04/22 11:38
     */
    @PostMapping("/register")
    public ResponseData register(@RequestBody Map<String,String> map, HttpServletRequest request){

        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        //验证码验证
        KaptchaCodeRequest kaptchaCodeRequest=new KaptchaCodeRequest();
          //从cookie中获取uuid
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setCode(captcha);
        kaptchaCodeRequest.setUuid(uuid);
        KaptchaCodeResponse kaptchaResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = kaptchaResponse.getCode();
        if (!code.equals(UserRetCode.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(kaptchaResponse.getMsg());
        }

        //验证成功---然后就是插入用户信息记录
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(email);
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);
        UserRegisterResponse response = registerService.register(userRegisterRequest);
        if (response.getCode().equals(UserRetCode.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(null);
        }
        //否则，说明service层有异常，进入了catch，执行了异常中的方法，给respone封装 erro信息
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

     @PostMapping("/login")
    public ResponseData login(@RequestBody  Map<String,String> map,HttpServletRequest request,HttpServletResponse servletResponse){
         String userName = map.get("userName");
         String userPwd = map.get("userPwd");
         String captcha = map.get("captcha");
         //1.验证码验证
         KaptchaCodeRequest codeRequest = new KaptchaCodeRequest();
         String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
         codeRequest.setUuid(uuid);
         codeRequest.setCode(captcha);
         KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(codeRequest);
         String code = kaptchaCodeResponse.getCode();
         if (!code.equals(UserRetCode.SUCCESS.getCode())){
             return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
         }
         //2.登录验证
         UserLoginRequest loginRequest = new UserLoginRequest();
         loginRequest.setUserName(userName);
         loginRequest.setPassword(userPwd);
         UserLoginResponse response = userService.login(loginRequest,servletResponse);

         if (response.getCode().equals(UserRetCode.SUCCESS.getCode())){
             return new ResponseUtil<>().setData(response);
         }
         //否则，说明service层有异常，进入了catch，执行了异常中的方法，给respone封装 erro信息
         return new ResponseUtil<>().setErrorMsg(response.getMsg());

     }

     @GetMapping("login")
    public ResponseData login(HttpServletRequest request,HttpServletResponse response){
        //获取请求头中的user_info
         String user_info = request.getHeader("user_info");
         if ((user_info == null) || ("".equals(user_info))){
             //todo
             return new ResponseUtil<>().setErrorMsg(UserRetCode.REQUEST_CHECK_FAILURE.getMessage());
         }
         //解析user_info
         Map<String,String> userInfoMap = (Map<String, String>) JSON.parse(user_info);
         String id = userInfoMap.get("id");
         String username = userInfoMap.get("username");

         UserLoginGetResponse loginGetResponse = new UserLoginGetResponse();
         loginGetResponse.setUid(id);
         loginGetResponse.setUsername(username);

         return new ResponseUtil<>().setData(loginGetResponse);
     }

     @RequestMapping ("verify")
    public ResponseData verify(@RequestParam Map<String,String> map){
        //获得uid和username的值
         String uuid = map.get("uid");
         String username = map.get("username");
         //修该用户表和用户验证的记录
         UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
         userVerifyRequest.setUuid(uuid);
         userVerifyRequest.setUserName(username);

         UserVerifyResponse response = userService.verify(userVerifyRequest);
         if (response.getCode().equals(UserRetCode.SUCCESS.getCode())){
             return new ResponseUtil<>().setData(response);
         }
         //否则，说明service层有异常或者其他错误，进入了catch，执行了异常中的方法，给respone封装 erro信息
         return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @RequestMapping("/loginOut")
    public ResponseData loginOut(HttpServletRequest request,HttpServletResponse response){
        //todo 改进
        //Cookie access_token = new Cookie("access_token", null);
        Cookie access_token = CookieUtil.genCookie("access_token", null, "/", 0);
        response.addCookie(access_token);
        //log.info("tonken放入成功：token{}",token);
        //response.addCookie(access_token);
        return new ResponseUtil<>().setData(null);
    }
}
